#!/usr/bin/python

import sys
import fcntl
import os
import re
import socket
import struct
import ctypes
import array
import math
import commands
import time
from optparse import OptionParser

SYSFS_NET_PATH = "/sys/class/net"
PROCFS_NET_PATH = "/proc/net/dev"

# From linux/sockios.h
SIOCGIFINDEX = 0x8933
SIOCGIFFLAGS =  0x8913
SIOCSIFFLAGS =  0x8914
SIOCGIFHWADDR = 0x8927
SIOCSIFHWADDR = 0x8924
SIOCGIFADDR = 0x8915
SIOCSIFADDR = 0x8916
SIOCGIFNETMASK = 0x891B
SIOCSIFNETMASK = 0x891C
SIOCETHTOOL = 0x8946

# From linux/if.h
IFF_UP       = 0x1

# From linux/socket.h
AF_UNIX      = 1
AF_INET      = 2

# From linux/ethtool.h
ETHTOOL_GSET = 0x00000001 # Get settings
ETHTOOL_SSET = 0x00000002 # Set settings
ETHTOOL_GLINK = 0x0000000a # Get link status (ethtool_value)
ETHTOOL_SPAUSEPARAM = 0x00000013 # Set pause parameters.

ADVERTISED_10baseT_Half = (1 << 0)
ADVERTISED_10baseT_Full =(1 << 1)
ADVERTISED_100baseT_Half = (1 << 2)
ADVERTISED_100baseT_Full = (1 << 3)
ADVERTISED_1000baseT_Half = (1 << 4)
ADVERTISED_1000baseT_Full = (1 << 5)
ADVERTISED_Autoneg = (1 << 6)
ADVERTISED_TP = (1 << 7)
ADVERTISED_AUI = (1 << 8)
ADVERTISED_MII = (1 << 9)
ADVERTISED_FIBRE = (1 << 10)
ADVERTISED_BNC = (1 << 11)
ADVERTISED_10000baseT_Full = (1 << 12)

# Globals
sock = None
sockfd = None

RESTART_NETWORK_SERVICE ="/etc/init.d/networking restart"
RESTART_NCARE_SERVICE ="/etc/init.d/ncare restart"
RESTART_ITOP_SERVICE ="/etc/init.d/itop restart"

IFCONFIG = 'ifconfig -a |grep Ethernet| awk -F\" \" \'{print $1}\''
START_HOSTNAME_SERVICE = "/usr/sbin/service hostname start" 

INTERFACE_FILE = '/etc/network/interfaces'
DNS_FILE = '/etc/resolv.conf'
HNAME_FILE = '/etc/hostname'

is_config_db = False
is_config_app = False
is_config_csn = False
is_config_all = False


DHCP_TEMPLATE = '''auto %s
iface %s inet dhcp
'''

STATIC_IP_TEMPLATE = '''auto %s
iface %s inet static
    address %s
    netmask %s
    gateway %s
'''


if not os.path.isdir(SYSFS_NET_PATH):
    raise ImportError("Path %s not found. This module requires sysfs." % SYSFS_NET_PATH)
if not os.path.exists(PROCFS_NET_PATH):
    raise ImportError("Path %s not found. This module requires procfs." % PROCFS_NET_PATH)

DATASTORE_DIRECTORIES = [
    '/ncare/data',
    '/ncare/av',
    '/ncare/EXBPAFiles',
    '/ncare/installer',
    '/ncare/mibfiles',
    '/ncare/recordings',
    '/ncare/wsus',
    '/scc',
    '/scc/file-repo',
    '/scc/profile-images',
    '/scc/reports',
    '/scc/resources',
    '/scc/salicense',
    '/scc/annotatedReports',
    '/scc/attachments',
    '/scc/cnocReports',
    '/scc/cpe_release_notes',
    '/scc/DeviceDetailsAbridgedReport',
    '/scc/DeviceDetailsReport',
    '/scc/downloadfiles',
    '/scc/endCustomerReports',
    '/scc/EndPointSecurityReports',
    '/scc/ncare-agent',
    '/scc/NetworkBackupSummaryReport',
    '/scc/newMonthlyExecutiveReports',
    '/scc/platform',
    '/scc/reports',
    '/scc/resources',
    '/scc/rsa',
    '/scc/URLMonitoringReport',
    '/scc/varExecutiveReports',
    '/scc/VARSLAConsolidatedReport',
    '/db/backups' ]

class Interface(object):
    ''' Class representing a Linux network device. '''

    def __init__(self, name):
        self.name = name

    def is_up(self):
        ''' Return True if the interface is up, False otherwise. '''

        # Get existing device flags
        ifreq = struct.pack('16sh', self.name, 0)
        flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1]

        # Set new flags
        if flags & IFF_UP:
            return True
        else:
            return False

    def get_ip(self):
        ifreq = struct.pack('16sH14s', self.name, AF_INET, '\x00'*14)
        try:
            res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)
        except IOError:
            return None
        ip = struct.unpack('16sH2x4s8x', res)[2]

        return socket.inet_ntoa(ip)

    def get_netmask(self):
        ifreq = struct.pack('16sH14s', self.name, AF_INET, '\x00'*14)
        try:
            res = fcntl.ioctl(sockfd, SIOCGIFNETMASK, ifreq)
        except IOError:
            return None
        netmask = socket.ntohl(struct.unpack('16sH2xI8x', res)[2])
        if netmask == 0:
            return None
        return ipv4_cidr_to_netmask(32 - int(math.log(ctypes.c_uint32(~netmask).value + 1, 2)))

    def get_mac(self):
        ''' Obtain the device's mac address. '''
        ifreq = struct.pack('16sH14s', self.name, AF_UNIX, '\x00'*14)
        res = fcntl.ioctl(sockfd, SIOCGIFHWADDR, ifreq)
        address = struct.unpack('16sH14s', res)[2]
        mac = struct.unpack('6B8x', address)

        return ":".join(['%02X' % i for i in mac])

    def get_index(self):
        ''' Convert an interface name to an index value. '''
        ifreq = struct.pack('16si', self.name, 0)
        res = fcntl.ioctl(sockfd, SIOCGIFINDEX, ifreq)
        return struct.unpack("16si", res)[1]


def iterifs(physical=True):
    ''' Iterate over all the bridges in the system. If physical is
        true, then return only real physical interfaces (not 'lo', etc).'''
    net_files = os.listdir(SYSFS_NET_PATH)
    for d in net_files:
        path = os.path.join(SYSFS_NET_PATH, d)
        if not os.path.isdir(path):
            continue
        if physical and not os.path.exists(os.path.join(path, "device")):
            continue
        yield Interface(d)

def listPhyifs():
    net_files = os.listdir(SYSFS_NET_PATH)
    ifs = []
    for d in net_files:
        path = os.path.join(SYSFS_NET_PATH, d)
        if not os.path.isdir(path):
            continue
        if not os.path.exists(os.path.join(path, "device")):
            continue
        ifs.append(d)
    return ifs

def findif(name):
    for br in iterifs(True):
        if name == br.name:
            return br
    return None

def list_ifs(physical=True):
    ''' Return a list of the names of the interfaces. If physical is
        true, then return only real physical interfaces (not 'lo', etc). '''
    return [br for br in iterifs(physical)]


def init():
    ''' Initialize the library '''
    globals()["sock"] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    globals()["sockfd"] = globals()["sock"].fileno()


def shutdown():
    ''' Shut down the library '''
    globals()["sock"].close()
    globals()["sock"] = None
    globals()["sockfd"] = None

def get_default_if():
    """ Returns the default interface """
    interf = "" 
    f = open ('/proc/net/route', 'r')
    for line in f:
        words = line.split()
        dest = words[1]
        try:
            if (int (dest) == 0):
                interf = words[0]
                break
        except ValueError:
            pass
    return interf

def get_default_gw():
    """ Returns the default gateway """
    octet_list = []
    gw_from_route = None
    f = open ('/proc/net/route', 'r')
    for line in f:
        words = line.split()
        dest = words[1]
        try:
            if (int (dest) == 0):
                gw_from_route = words[2]
                break
        except ValueError:
            pass
        
    if not gw_from_route:
        return None 
    
    for i in range(8, 1, -2):
        octet = gw_from_route[i-2:i]
        octet = int(octet, 16)
        octet_list.append(str(octet)) 
    
    gw_ip = ".".join(octet_list)
            
    return gw_ip

def getSSLProps(file):
    keyFile = ""
    keyPass = ""
    if os.path.exists(file):
        ssl_file = open(file, 'r')
        for line in ssl_file.readlines():
            line = line.strip()
            if line.find("keystorePass") != -1:
                keyPass = line.split("=")[1].strip("\"")
            if line.find("keystoreFile") != -1:
                keyFile = line.split("=")[1].strip("\"")                    
        ssl_file.close
    else:
        return "", ""
    return keyFile.strip(), keyPass.strip()

def static_ip(eth, IP_ADDRESS, NETMASK, GATEWAY, dns1,dns2):

    static_message = '''auto %s
iface %s inet static
    address %s
    netmask %s''' % (eth,eth ,IP_ADDRESS, NETMASK)
    if GATEWAY != '':
        static_message = static_message + "\n    " + "gateway " + GATEWAY
    if dns1 != '':
        static_message = static_message + "\n    " + "dns-nameservers " + dns1
    if dns2 != '':
        static_message = static_message + " " + dns2
    static_message  = static_message + "\n"
    return static_message

def config_timedate():
    ntp1 = raw_input('\nNTP Server 1 : ').strip()
    while ntp1 == '':
        print '\n Provide proper ntp server!'
        ntp1 = raw_input('\nNTP Server 1 : ').strip() 
        
    ntp2 = raw_input('NTP Server 2 : ').strip()
    while ntp2 == '':
        print '\n Provide proper ntp server!'
        ntp2 = raw_input('\nNTP Server 2 : ').strip()   
    
    print '\n\nWould you like to continue with following settings'
    print '**********************'
    print "NTP Server 1 :", ntp1
    print "NTP Server 2 :", ntp2
    print '**********************'
    is_proper = raw_input('\nIs setting proper? (y/n)> ').strip()
    while is_proper != 'y' and is_proper != 'n':
        is_proper = raw_input("Provide the correct option..\nIs above setting proper(y/n)> ").strip()

    if is_proper == 'y':
        commands.getstatusoutput('service ntp stop')
        retVal , output = commands.getstatusoutput('ntpdate -u %s' % ntp1)
        print "Tried to sync with server %s - %s" %(ntp1 , output)
        if retVal != 0:
            retVal , output = commands.getstatusoutput('ntpdate -u %s' % ntp2)
            print "Tried to sync with server %s - %s" %(ntp2 , output)
        
        ntp_command = '''sed -e 's/$ntpserver1/%s/g' -e 's/$ntpserver2/%s/g' /opt/scripts/templates/ntp.conf > /etc/ntp.conf''' % (ntp1, ntp2)
        commands.getstatusoutput(ntp_command)
        commands.getstatusoutput('service ntp restart')

def show_timedate():
    ntp_server1 = None
    ntp_server2 = None
    retVal , output = commands.getstatusoutput('date')
    for line in file('/etc/ntp.conf', 'r'): 
        line = line.strip()
        if line.startswith("server"):
            if ntp_server1:
                ntp_server2 = line.split()[1]
                break
            else:
                ntp_server1 = line.split()[1]
                
    print
    print "Current Time:", output
    print "NTP Servers : %s %s" % (ntp_server1, ntp_server2) 
          
def show_snmp():
    retVal, output = commands.getstatusoutput('grep ^rocommunity /etc/snmp/snmpd.conf | awk \'{print $2}\'')
    print
    print "SNMP community : ",output
             
def config_snmp():
    community = raw_input("SNMP Community: ").strip()
    while community == '':
        mail_server = raw_input("SNMP Community: ").strip()

    print '\n\nWould you like to continue with following settings'
    print '**********************'
    print "SNMP Community:", community
    print '**********************'

    is_proper = raw_input('\nIs setting proper? (y/n)> ').strip()
    while is_proper != 'y' and is_proper != 'n':
        is_proper = raw_input("Provide the correct option..\nIs above setting proper(y/n)> ").strip()

    if is_proper == 'y':
        cmd = "sed -i \'s/^rocommunity.*$/rocommunity\t" + community + "/g\' /etc/snmp/snmpd.conf"
        commands.getstatusoutput(cmd)
        commands.getstatusoutput('service snmpd restart')
    
def show_SSL():
    ssl_props_file = "/opt/%s/conf/SSLCert.properties"
    key_file = ""
    key_phrase = ""
    if is_config_all or is_config_app:
        key_file, key_phrase = getSSLProps(ssl_props_file % "itop")
    elif is_config_csn and os.path.exists("/etc/monit/conf.d/ncare.monitrc"):
        key_file, key_phrase = getSSLProps(ssl_props_file % "ncare")
    print
    print "SSL Certificate file : ",key_file
    print "SSL Certificate pass phrase : ",key_phrase

def config_SSL():
    init()
    interfaces_parser()

    ifaces = listPhyifs()
    ssl_file = raw_input('\nSSL Certificate file : ').strip()
    while ssl_file == '':
        print '\n Provide proper SSL Certificate file!'
        ssl_file = raw_input('\nSSL Certificate file : ').strip() 
        
    ssl_phrase = raw_input('SSL Certificate pass phrase : ').strip()
    while ssl_phrase == '':
        print '\n Provide SSL Certificate pass phrase!'
        ssl_phrase = raw_input('\nSSL Certificate pass phrase : ').strip()   
    
    print '\n\nWould you like to continue with following settings'
    print '**********************'
    print "SSL Certificate file :", ssl_file
    print "SSL Certificate pass phrase :", ssl_phrase
    print '**********************'
    is_proper = raw_input('\nIs setting proper? (y/n)> ').strip()
    while is_proper != 'y' and is_proper != 'n':
        is_proper = raw_input("Provide the correct option..\nIs above setting proper(y/n)> ").strip()

    if os.path.exists("/etc/monit/conf.d/itop.monitrc") and is_config_all:
        if 'eth0' in ifaces:
            ip1 = Interface('eth0').get_ip()
        else:
            ip1 = ""
        itop_file = open('/opt/itop/conf/SSLCert.properties','w')
        itop_file.write("keystoreFile=\"" + ssl_file + "\"\n")
        itop_file.write("keystorePass=\"" + ssl_phrase + "\"")
        itop_file.close
        commands.getstatusoutput("/bin/chmod 777 /opt/itop/conf/SSLCert.properties")        
        if ip1 != "":
            itop_command = '''sed -e 's/@ITOP_IP@/%s/g' -e 's/@SSL_FILE@/%s/g' -e 's/@SSL_PASS@/%s/g' /opt/itop/conf/server-eVistara-tpl.xml > /opt/itop/conf/server.xml''' % (ip1, ssl_file, ssl_phrase)
            commands.getstatusoutput(itop_command)
            commands.getstatusoutput("chmod 755 /opt/itop/conf/server.xml")
            commands.getstatusoutput("chown itop.itop /opt/itop/conf/server.xml")
            print 'Restarting itop service...'
            msg = os.popen('/etc/init.d/itop stop')
            for line in msg.readlines():
                print line
            time.sleep(5)
            msg = os.popen('/etc/init.d/itop start')
            for line in msg.readlines():
                print line
            print "\n\nITOP has been restarted after SSL configuration change.."
        else:
            print "Configure interface properly for ITOP service needs"

    if is_config_app:
        itop_file = open('/opt/itop/conf/SSLCert.properties','w')
        itop_file.write("keystoreFile=\"" + ssl_file + "\"\n")
        itop_file.write("keystorePass=\"" + ssl_phrase + "\"")
        itop_file.close
        itop_command = '''sed -e 's/address=\"@ITOP_IP@\"//g' -e 's/@SSL_FILE@/%s/g' -e "s/@SSL_PASS@/%s/g" /opt/itop/conf/server-eVistara-tpl.xml > /opt/itop/conf/server.xml''' % (ssl_file, ssl_phrase)
        commands.getstatusoutput(itop_command)
        commands.getstatusoutput("chmod 755 /opt/itop/conf/server.xml")
        commands.getstatusoutput("chown itop.itop /opt/itop/conf/server.xml")
        print 'Restarting itop service...'
        msg = os.popen('/etc/init.d/itop stop')
        for line in msg.readlines():
            print line
        time.sleep(5)
        msg = os.popen('/etc/init.d/itop start')
        for line in msg.readlines():
            print line
        print "\n\nITOP has been restarted after SSL configuration change.."

    if os.path.exists("/etc/monit/conf.d/ncare.monitrc"):
        if 'eth2' in ifaces and 'eth3' in ifaces:
            print "Using eth2 and eth3 for ncare service"
            ip2 = Interface('eth2').get_ip()
            ip3 = Interface('eth3').get_ip()
        elif 'eth1' in ifaces and 'eth2' in ifaces: 
            print "Using eth1 and eth2 for ncare service"
            ip2 = Interface('eth1').get_ip()
            ip3 = Interface('eth2').get_ip()
        else:
            ip2 = ""
            ip3 = ""
        
        if ip2 != "" and ip3 != "":
            ncare_file = open('/opt/ncare/conf/SSLCert.properties','w')
            ncare_file.write("keystoreFile=\"" + ssl_file + "\"\n")
            ncare_file.write("keystorePass=\"" + ssl_phrase + "\"")
            ncare_file.close
            commands.getstatusoutput("/bin/chmod 777 /opt/ncare/conf/SSLCert.properties")

            if is_config_all:
                ncare_command = '''sed -e 's/@HTTP_IP@/%s/g' -e 's/@TLS_IP@/%s/g' -e 's/@SSL_FILE@/%s/g' -e 's/@SSL_PASS@/%s/g' /opt/ncare/conf/ncare-eVistara-tpl.xml > /opt/ncare/conf/ncare.xml''' % (ip2, ip3, ssl_file, ssl_phrase)
            else:
                ncare_command = '''sed -e 's/@HTTP_IP@/%s/g' -e 's/@TLS_IP@/%s/g' -e 's/@SSL_FILE@/%s/g' -e 's/@SSL_PASS@/%s/g' /opt/ncare/conf/ncare.xml.tpl > /opt/ncare/conf/ncare.xml''' % (ip2, ip3, ssl_file, ssl_phrase)
            commands.getstatusoutput(ncare_command)
            commands.getstatusoutput("chmod 755 /opt/ncare/conf/ncare.xml")
            commands.getstatusoutput("chown itop.itop /opt/ncare/conf/ncare.xml")
            print 'Restarting ncare service...'
            msg = os.popen('/etc/init.d/ncare stop')
            for line in msg.readlines():
                print line
            time.sleep(5)
            msg = os.popen('/etc/init.d/ncare start')
            for line in msg.readlines():
                print line
            print "\n\nNCare has been restarted after SSL configuration change.."
        else:
            print "Configure interface properly for ncare service needs"

def show_systemparam():
    if hasattr(socket, 'setdefaulttimeout'):
        socket.setdefaulttimeout(5)

    if not is_config_db and not is_config_app:
        try:
            apps_ip = socket.gethostbyname('itop-app.com')
        except:
            apps_ip = "**Not Configured**"
        
        if os.path.exists('/opt/admin/conf/NATIP'):
            nat_file = open('/opt/admin/conf/NATIP','r')
            nat_address = nat_file.readline().strip()      
            nat_file.close
        else:
            nat_address = None

    if not is_config_db and not is_config_csn:
        try:
            se_ip = socket.gethostbyname('itop-se')
        except:
            se_ip = "**Not Configured**"

    if not is_config_db:
        try:
            db_ip = socket.gethostbyname('itop-db')
        except:
            db_ip = "**Not Configured**"
        try:
            db_node_hostname = commands.getstatusoutput('cat /etc/hosts | grep kafka | awk -F\' \'  \'{print $NF}\'')[1]
        except Exception, emsg:
            db_node_hostname = "**Not Configured**"
        if db_node_hostname.strip() == "kafka":
            db_node_hostname = "**Not Configured**"
    
    print 
    if not is_config_db and not is_config_app:
        print "Web Server IP   :", apps_ip
        if nat_address:
            print "Compute Node(CS) IP Address  :", nat_address
    if not is_config_db:
        print "DB Server IP		:", db_ip
        print "DB Server Hostname	:", db_node_hostname
    if not is_config_db and not is_config_csn:
        print "Search Engine IP	:", se_ip
    
    

def validateEmail(email):
    if len(email) > 6:
        if re.match("^[\w\.-]+@[\w\.-]+\.\w{2,4}$", email) != None:
            return True
    return False


eth_mode = {}
eth_section = {}
def interfaces_parser():
    global eth_mode
    global eth_section
    eth_mode = {}
    eth_section = {}
    interfaces_text = open(INTERFACE_FILE, 'r').read()
    reobj = re.compile("(?:auto|allow-|iface|up route|source|mapping)(?:(?!(?:auto|allow-|iface|up route|source|mapping)).)*(?<!\s)", re.DOTALL)
    sections = reobj.findall(interfaces_text)
    for section in sections:
        if section.startswith('iface '):
            words =  (section.split('\n'))[0].split()
            if words[1] == 'lo':
               continue
            if words[2] == 'inet':
               eth_mode[words[1]] = words[3]
               eth_section[words[1]] = "auto %s\n%s\n" % (words[1], section)


def show_mailrelay():
    retVal, output = commands.getstatusoutput('grep ^DS /etc/mail/sendmail.cf | sed "s/^DS//"')
    if len(output.splitlines()) == 0:
        mail_server = ""
    else:
        mail_server = output.splitlines()[0]
    print "\nMailserver Relay :", mail_server

def config_mailrelay():
    mail_server = raw_input("Mail Server Relay: ").strip()
    while mail_server == '':
        mail_server = raw_input("Mail Server Relay: ").strip()

    print '\n\nWould you like to continue with following settings'
    print '**********************'
    print "Mail Server Relay:", mail_server
    print '**********************'

    is_proper = raw_input('\nIs setting proper? (y/n)> ').strip()
    while is_proper != 'y' and is_proper != 'n':
        is_proper = raw_input("Provide the correct option..\nIs above setting proper(y/n)> ").strip()

    if is_proper == 'y':
        commands.getstatusoutput('sed -i \"/SMART_HOST/d\" /etc/mail/sendmail.mc')
        mail_entry = "sed -i " + "\"$ a\define(\`SMART_HOST\',\`" + mail_server + "\')dnl\"" + " /etc/mail/sendmail.mc"
        commands.getstatusoutput(mail_entry)
        commands.getstatusoutput('cd /etc/mail/ && m4 sendmail.mc > sendmail.cf')
        commands.getstatusoutput('service sendmail restart')
      


def show_network():
    init()
    interfaces_parser()
    msg = os.popen(IFCONFIG)
    for line in msg.readlines():
        inf = Interface(line.strip())
        print "\n\nInterface %s" % line.strip()
        if eth_mode.has_key(line.strip()):
            mode = eth_mode[line.strip()]
        else:
            mode = "UNKNOWN"   
        print '\tAcquisition Mode : %s' % mode
        print "\tIP Address       : %s" % inf.get_ip()
        print "\tNM Address       : %s" % inf.get_netmask()
        print "\tMAC Address      : %s" % inf.get_mac()

    print "\nDefault Gateway  : %s (%s) " % (get_default_gw(), get_default_if())
    print 'Hostname         : %s' % socket.gethostname()

def show_nfs_detail():
    retVal , output = commands.getstatusoutput('mount | grep /opt/datastore')        
    if retVal == 0:
        retVal , output = commands.getstatusoutput('df -Pk /opt/datastore')        
        if retVal == 0:
            print "\nMount Point /opt/datastore is in OK state. Here is its detail"
            print
            print output
        else:
            print "\nMount Point /opt/datastore is not in OK state"
    else:
        print "\nMount Point /opt/datastore is not in OK state"

def config_systemparam():

    if not is_config_db and not is_config_app:
        apps_ip = raw_input('\nWeb Server IP Address: ').strip()
        while is_valid_ipv4_address(apps_ip) is not True:
            print '\nInvalid IP address!'
            apps_ip = raw_input('\nWeb Server IP Address: ').strip()
        
        if os.path.exists('/opt/admin/conf/NATIP'):
            nat_ip = raw_input('Compute Node(CS) IP Address: ').strip()
            while nat_ip == '':
                print '\n Provide proper public address!'
                nat_ip = raw_input('\nCompute Node(CS) IP Address: ').strip()       
        else:
            nat_ip = None 

    if not is_config_db:
        db_ip = raw_input('DB Server IP Address: ').strip()
        while is_valid_ipv4_address(db_ip) is not True:
            print '\nInvalid IP address!'
            db_ip = raw_input('DB Server IP Address: ').strip()
        db_node_hostname = raw_input('Messaging/DB server hostname: ').strip()
        while db_node_hostname == '':
            db_node_hostname = raw_input('Messaging/DB server hostname: ').strip()
    
    if not is_config_db and not is_config_csn:
        se_ip = raw_input('Search Engine IP Address: ').strip()
        while is_valid_ipv4_address(se_ip) is not True:
            print '\nInvalid IP address!'
            se_ip = raw_input('Search Engine IP Address: ').strip()

    email = raw_input('Email on which notification will be sent: ').strip()
    while validateEmail(email) is not True:
        print '\nInvalid Email!'
        email = raw_input('Email address: ').strip()


    print '\n\nWould you like to continue with following settings'
    print '**********************'
    if not is_config_db and not is_config_app:
        print "Web Server   :", apps_ip
        if nat_ip != None:
            print "NAT Address  :", nat_ip
    if not is_config_db:
        print "DB Server    :", db_ip
        print "Messaging/DB server hostname:", db_node_hostname
    if not is_config_db and not is_config_csn:
        print "Search Engine:", se_ip

    print "Email address:", email
    print '**********************'
    is_proper = raw_input('\nIs setting proper? (y/n)> ').strip()
    while is_proper != 'y' and is_proper != 'n':
        is_proper = raw_input("Provide the correct option..\nIs above setting proper(y/n)> ").strip()

    if is_proper == 'y':
        if not is_config_db:
            db_entry1 = "sed -i " + "\"2 a\\" + db_ip + "    msp-db cassandra-db msp_report-db aggregator-db dra-db ncare-db tickets-db itop-db" + "\" /etc/hosts"
            commands.getstatusoutput('sed -i \"/itop-db$/d\" /etc/hosts')
            commands.getstatusoutput(db_entry1)
            db_entry2 = "sed -i " + "\"2 a\\" + db_ip + "    mongo mongodb mongo-db mongo-db1 mongo-db2 membase kafka " + db_node_hostname + "\" /etc/hosts"
            commands.getstatusoutput('sed -i \"/kafka/d\" /etc/hosts')
            commands.getstatusoutput(db_entry2)
        if not is_config_db and not is_config_app:
            web_entry = "sed -i " + "\"2 a\\" + apps_ip + "    mspnocsupport.com itop-app.com" + "\" /etc/hosts"
            commands.getstatusoutput('sed -i \"/itop-app.com$/d\" /etc/hosts')
            commands.getstatusoutput(web_entry)
            
            if nat_ip != None: 
                nat_file = open('/opt/admin/conf/NATIP','w')
                nat_address = nat_file.write(nat_ip)      
                nat_file.close
        if not is_config_db and not is_config_csn:
            se_entry = "sed -i " + "\"3 a\\" + se_ip + "    itop-se" + "\" /etc/hosts"
            commands.getstatusoutput('sed -i \"/itop-se$/d\" /etc/hosts')
            commands.getstatusoutput(se_entry)

        if not is_config_db:
            email_entry = "sed -i " + "\"s/^set alert.*/set alert " + email + " only on { timeout }/g" + "\" /etc/monit/monitrc"
            commands.getstatusoutput(email_entry)
            commands.getstatusoutput('monit reload')

       
 
def umount_nfs():
    retVal, output = commands.getstatusoutput('mount | grep /opt/datastore') 
    if retVal == 0:
        retVal1 , output = commands.getstatusoutput('umount /opt/datastore')        
        if retVal1 != 0:
            retVal2 , output = commands.getstatusoutput('umount -f /opt/datastore')        
            if retVal2 != 0:
                return False
    return True

def config_mountpoint():
    nfs_server = raw_input('\nEnter NFS Server IP: ').strip()
    while is_valid_ipv4_address(nfs_server) is not True:
        print '\nInvalid IP address!'
        nfs_server = raw_input('\nEnter NFS Server IP: ').strip()
    nfs_share =  raw_input('Enter NFS Share    : ').strip()
    print '\n\nWould you like to continue with following settings'
    print '\n***** Mount Point *****'
    print "NFS Server:", nfs_server 
    print "NFS Share :", nfs_share 
    print '**********************'
    is_proper = raw_input('\nIs setting proper? (y/n)> ').strip()
    while is_proper != 'y' and is_proper != 'n':
        is_proper = raw_input("Provide the correct option..\nIs above setting proper(y/n)>").strip()

    if is_proper == 'y':
        try:
            nfs_setting = '''dnsname=fileserver\nip=%s\nformat=ext3\nshare=%s\nlocalmountpath=/opt/datastore'''
            nfs_file = open('/opt/admin/bin/nfs/mount_details', 'w')
            nfs_text = nfs_setting % (nfs_server, nfs_share)
            nfs_file.write(nfs_text);
            nfs_file.close
        except:
            pass 
        nfs_entry = '''echo \"%s:%s /opt/datastore nfs rsize=8192,wsize=8192,timeo=14,intr\" >> /etc/fstab''' % (nfs_server, nfs_share)
        commands.getstatusoutput('sed -i \"/\/opt\/datastore/d\" /etc/fstab')
        commands.getstatusoutput(nfs_entry)
        if umount_nfs():
            mnt_cmd = "mount %s:%s /opt/datastore" % (nfs_server, nfs_share)
            result, output = commands.getstatusoutput(mnt_cmd)
            if result == 0:
                if not os.path.exists("/opt/datastore/ncare") or not os.path.exists("/opt/datastore/db"):
                    for dir in DATASTORE_DIRECTORIES:
                        commands.getstatusoutput("mkdir -p /opt/datastore" + dir.strip())
                    commands.getstatusoutput("chmod -R 777 /opt/datastore")
                    print "Created NFS directory structure."
                else:
                    print "NFS directory structure already created."
            else:
                print "Failed to mount the NFS share. " + output

def config_ethernet():
    #msg = os.popen(IFCONFIG)
    ifaces = listPhyifs()
    ip_settings = '''auto lo
iface lo inet loopback\n'''

    for line in ifaces:
        ip_setting = get_dhcp_input(line)
        ip_settings = ip_settings + '\n' + ip_setting


    hname_setting = ''
    is_hname = raw_input('\nWould you like to configure hostname? (y/n)> ').strip()
    if is_hname == 'y':
        HOSTNAME = raw_input("Hostname: ").strip()
        while HOSTNAME == '':
            HOSTNAME = raw_input("Hostname: ").strip()

        hname_setting = HOSTNAME

    print '\n\nWould you like to continue with following settings'
    print '\n***** IP Setting *****'
    print ip_settings
    print '**********************'
    is_proper = raw_input('\nIs setting proper? (y/n)> ').strip()
    while is_proper != 'y' and is_proper != 'n':
        is_proper = raw_input("Provide the correct option..\nIs above setting proper(y/n)> ").strip()
    
    if is_proper == 'y':
        write_file(ip_settings, hname_setting)
        print 'Restarting network service...'
        msg = os.popen(RESTART_NETWORK_SERVICE)
        for line in msg.readlines():
            print line
        print "\n\nConfiguration has been done.."
        
        if os.path.exists("/etc/monit/conf.d/itop.monitrc") and is_config_all:
            if 'eth0' in ifaces:
                ip1 = Interface('eth0').get_ip()
            else:
                ip1 = ""
            sslFile = "vistara.ks.p12" 
            sslPass = "N3t@dmin"
            sslFile, sslPass = getSSLProps("/opt/itop/conf/SSLCert.properties")
            if ip1 != "":
                itop_command = '''sed -e 's/@ITOP_IP@/%s/g' -e 's/@SSL_FILE@/%s/g' -e 's/@SSL_PASS@/%s/g' /opt/itop/conf/server-eVistara-tpl.xml > /opt/itop/conf/server.xml''' % (ip1, sslFile, sslPass)
                commands.getstatusoutput(itop_command)
                commands.getstatusoutput("chmod 755 /opt/itop/conf/server.xml")
                commands.getstatusoutput("chown itop.itop /opt/itop/conf/server.xml")
                print 'Restarting itop service...'
                msg = os.popen('/etc/init.d/itop stop')
                for line in msg.readlines():
                    print line
                time.sleep(5)
                msg = os.popen('/etc/init.d/itop start')
                for line in msg.readlines():
                    print line
                print "\n\ITOP has been restarted after network configuration change.."
            else:
                print "Configure interface properly for ITOP service needs"
        
        if os.path.exists("/etc/monit/conf.d/ncare.monitrc"):
            if 'eth2' in ifaces and 'eth3' in ifaces:
                print "Using eth2 and eth3 for ncare service"
                ip2 = Interface('eth2').get_ip()
                ip3 = Interface('eth3').get_ip()
            elif 'eth1' in ifaces and 'eth2' in ifaces: 
                print "Using eth1 and eth2 for ncare service"
                ip2 = Interface('eth1').get_ip()
                ip3 = Interface('eth2').get_ip()
            else:
                ip2 = ""
                ip3 = ""
            
            sslFile = "vistara.ks.p12" 
            sslPass = "N3t@dmin"
            sslFile, sslPass = getSSLProps("/opt/ncare/conf/SSLCert.properties")
            if ip2 != "" and ip3 != "":
                if is_config_all:
                    ncare_command = '''sed -e 's/@HTTP_IP@/%s/g' -e 's/@TLS_IP@/%s/g' -e 's/@SSL_FILE@/%s/g' -e 's/@SSL_PASS@/%s/g' /opt/ncare/conf/ncare-eVistara-tpl.xml > /opt/ncare/conf/ncare.xml''' % (ip2, ip3, sslFile, sslPass)
                else:
                    ncare_command = '''sed -e 's/@HTTP_IP@/%s/g' -e 's/@TLS_IP@/%s/g' -e 's/@SSL_FILE@/%s/g' -e 's/@SSL_PASS@/%s/g' /opt/ncare/conf/ncare.xml.tpl > /opt/ncare/conf/ncare.xml''' % (ip2, ip3, sslFile, sslPass)
                commands.getstatusoutput(ncare_command)
                commands.getstatusoutput("chmod 755 /opt/ncare/conf/ncare.xml")
                commands.getstatusoutput("chown itop.itop /opt/ncare/conf/ncare.xml")
                print 'Restarting ncare service...'
                msg = os.popen('/etc/init.d/ncare stop')
                for line in msg.readlines():
                    print line
                time.sleep(5)
                msg = os.popen('/etc/init.d/ncare start')
                for line in msg.readlines():
                    print line
                print "\n\nNCare has been restarted after network configuration change.."
            else:
                print "Configure interface properly for ncare service needs"
    else:
        print "Exiting..."
     

def get_dhcp_input(eth):
    eth = eth.strip('\n')
    print '\n\nConfiguring %s' % eth
    print "--------------------"
    is_dhcp = raw_input('\n[N]o config, [D]HCP, [S]tatic? (N/D/S)> ').strip()
    
    dns_setting = ''
    
    while is_dhcp != 'D' and is_dhcp != 'N' and is_dhcp != 'S':
        is_dhcp = raw_input("Provide the correct option..(N/D/S)> ").strip()
        
    if is_dhcp == 'D':
        ip_setting = DHCP_TEMPLATE % (eth,eth)
    elif is_dhcp == 'N':
        if eth_section.has_key(eth):
            ip_setting = eth_section[eth]
        else:
            ip_setting = ''
    else:
        IP_ADDRESS = raw_input('\nIP Address    : ').strip()  
        while is_valid_ipv4_address(IP_ADDRESS) is not True:
            print '\nInvalid IP address!'
            IP_ADDRESS = raw_input('IP Address    : ').strip()         
            
        
        NETMASK = raw_input('Netmask       : ').strip()                   
        while is_valid_netmask_address(NETMASK) is not True:
            print '\nInvalid Netmask address!'
            NETMASK = raw_input('\nNetmask       : ').strip()            
        
        GATEWAY = raw_input('Gateway       : ').strip()
        if GATEWAY != '':
            while is_valid_ipv4_address(GATEWAY) is not True:
                print '\nInvalid Gateway address!'
                GATEWAY = raw_input('Gateway       : ').strip()
                if GATEWAY == '':
                    break
        
        dns_input = raw_input('DNS Server 1  : ').strip()
        if dns_input != '':
            while is_valid_ipv4_address(dns_input) is not True:
                print '\nInvalid DNS Server address!'
                dns_input = raw_input('DNS Server 1  : ').strip()
                if dns_input == '':
                    break
            
        dns1 = dns_input
        dns2 = ''
        if dns1 != '':
            dns_input = raw_input('DNS Server 2  : ').strip()
            if dns_input != '':
                while is_valid_ipv4_address(dns_input) is not True:
                    print '\nInvalid DNS Server address!'
                    dns_input = raw_input('DNS Server 2  : ').strip()
                    if dns_input == '':
                        break
            dns2 = dns_input
            
        ip_setting = static_ip( eth, IP_ADDRESS, NETMASK, GATEWAY, dns1,dns2)
    
    return ip_setting 

def get_dns_input():
    dns_setting = ''
    dns_server = ''
    dns_input = ''
    dns_input = raw_input('\nDNS Server 1: ').strip()
    while is_valid_ipv4_address(dns_input) is not True:
        print '\nInvalid DNS Server address!'
        dns_input = raw_input('\nDNS Server 1: ').strip()           

    dns_server = 'nameserver ' + dns_input

    dns_input = raw_input('\nDNS Server 2 (optional): ').strip()
    while dns_input!='' and is_valid_ipv4_address(dns_input) != True:
        print '\nInvalid IP address!'
        dns_input = raw_input('\nDNS Server 2 (optional): ').strip()            
    if dns_input != '':
        dns_server = dns_server + '\nnameserver ' + dns_input
        
    dns_search = raw_input('\nDNS search domain (optional): ').strip()
             
    dns_search = dns_search.strip()      
    if dns_search != '':
        dns_setting = 'search %s' % dns_search + '\n'
        
    dns_setting = dns_setting + dns_server
    return dns_setting
            
def write_file(ip_setting, hname_setting):
    interface_file = open(INTERFACE_FILE, 'w')
    interface_file.write(ip_setting);
    interface_file.close
    
    if hname_setting != '':
        hname_command = "hostname " + hname_setting
        os.popen(hname_command)
        hname_file = open(HNAME_FILE,'w')
        hname_file.write(hname_setting)        
        hname_file.close
        os.popen('sed -i "/^127.0.1.1/{s/^.*$/127.0.1.1\t%s/g;}" /etc/hosts' % hname_setting)
        os.popen(START_HOSTNAME_SERVICE)


def ipFormatChk(ip_str):
    pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
    if re.match(pattern, ip_str):
       return True
    else:
       return False

def is_valid_ipv4_address(address):
    try:
        addr= socket.inet_pton(socket.AF_INET, address)
    except AttributeError: # no inet_pton here, sorry
        try:
            addr= socket.inet_aton(address)
        except socket.error:
            return False
        return address.count('.') == 3
    except socket.error: # not a valid address
        return False

    return True

def ipv4_cidr_to_netmask(bits):
    """ Convert CIDR bits to netmask """
    netmask = ''
    for i in range(4):
        if i:
            netmask += '.'
        if bits >= 8:
            netmask += '%d' % (2**8-1)
            bits -= 8
        else:
            netmask += '%d' % (256-2**(8-bits))
            bits = 0
    return netmask

def is_valid_netmask_address(netmask):
    return netmask in map(lambda x: ipv4_cidr_to_netmask(x), range(1,33))

if __name__ == '__main__':
    usage = "usage: %prog [options]"
    parser = OptionParser(usage=usage)
    parser.add_option("-d", "--db",action="store_true", dest="is_config_db", 
                      default=False,help="For Database configuration")
    
    parser.add_option("-a", "--app",action="store_true", dest="is_config_app", 
                      default=False,help="For app server configuration")
    
    parser.add_option("-c", "--csn",action="store_true", dest="is_config_csn", 
                      default=False,help="For connection server configuration")

    parser.add_option("-A", "--all",action="store_true", dest="is_config_all", 
                      default=False,help="For connection server configuration")

    options, args = parser.parse_args()
    is_config_db = options.is_config_db
    is_config_app = options.is_config_app
    is_config_csn = options.is_config_csn
    is_config_all = options.is_config_all


    if (is_config_db and is_config_app) or (is_config_db and is_config_csn) or (is_config_app and is_config_csn) or (is_config_all and is_config_app) or (is_config_db and is_config_all) or (is_config_csn and is_config_all):
        print "Options -d, -a, -A and -c are mutual exclusive"
        sys.exit(1)
   
    while True:
        is_config = raw_input('\nConfigure [N]etwork, NFS [M]ount, [S]ystem Setting, [A]pplicaton Status, SNMP [C]ommunity, SS[L] Certificate, [T]ime Sync, [E]mail Relay, [R]eboot, [Q]uit (N/M/S/A/C/L/T/E/R/Q)> ').strip()
        while is_config != 'N' and is_config != 'M' and is_config != 'S' and is_config != 'Q' and is_config != 'R' and is_config != 'A'  and is_config != 'T' and is_config != 'E' and is_config != 'C' and is_config != 'L':
            is_config = raw_input("Provide the correct option (N/M/S/A/R/E/C/L/T/Q)> ").strip()
    
        if is_config == 'N':
            show_network()
            is_config = raw_input ('\nWould you like to configure network setting(y/n)> ').strip()

            while is_config != 'y' and is_config != 'n':
                is_config = raw_input("Provide the correct option (y/n)> ").strip()

            if is_config == 'y':
                config_ethernet()
                show_network()

        elif is_config == 'M':
            #if is_config_db:
            #    print "NSF mount is not needed to be configured in this node"
            #    continue

            show_nfs_detail()

            is_config = raw_input ('\nWould you like to configure mount point(y/n)> ').strip()
            while is_config != 'y' and is_config != 'n':
                is_config = raw_input("Provide the correct option (y/n)> ").strip()

            if is_config == 'y':
                config_mountpoint()
                show_nfs_detail()

        elif is_config == 'S':
            show_systemparam()
            is_config = raw_input ('\nWould you like to configure system parameters(y/n)> ').strip()
            while is_config != 'y' and is_config != 'n':
                is_config = raw_input("Provide the correct option (y/n)> ").strip()

            if is_config == 'y':
                config_systemparam()
                show_systemparam()
        
        elif is_config == 'C':
            show_snmp()
            is_config = raw_input ('\nWould you like to configure SNMP community(y/n)> ').strip()
            while is_config != 'y' and is_config != 'n':
                is_config = raw_input("Provide the correct option (y/n)> ").strip()

            if is_config == 'y':
                config_snmp()
                show_snmp()
        
          
        elif is_config == 'R':
            is_reboot =  raw_input ('\nDo you want to reboot the server(y/n)> ').strip()
            while is_reboot != 'y' and is_reboot != 'n':
                is_reboot = raw_input("Provide the correct option (y/n)> ").strip()

            if is_reboot == 'y':
                commands.getstatusoutput('reboot') 
                sys.exit(0)

        elif is_config == 'A':
            if is_config_db or is_config_all:
                retVal , output = commands.getstatusoutput('/usr/sbin/service mysql status')   
                if retVal == 0:
                    print "\nMysql Database is running.."    
                else:
                    print "\nMysql Database is not running.."    
                retVal , output = commands.getstatusoutput('/usr/sbin/service memcached status')   
                if retVal == 0:
                    print "Memcache daemon is running.."    
                else:
                    print "Memcache daemon is not running.."    
                retVal , output = commands.getstatusoutput('/usr/sbin/service mongodb status | grep running')   
                if retVal == 0:
                    print "Mongo DB is running.."    
                else:
                    print "Mongo DB is not running.."    
                retVal , output = commands.getstatusoutput('/usr/sbin/service kafka status | grep Running')   
                if retVal == 0:
                    print "Kafka is running.."    
                else:
                    print "Kafka is not running.."    
                retVal , output = commands.getstatusoutput('/usr/sbin/service zk status | grep Running')   
                if retVal == 0:
                    print "zookeeper is running.."
                else:
                    print "zookeeper is not running.."    
                retVal , output = commands.getstatusoutput("/usr/sbin/service cassandra status | grep 'is running'")
                if retVal == 0:
                    print "Cassandra is running.."
                else:
                    print "Cassandra is not running.."    
 
            if is_config_all or not is_config_db:
                retVal , output = commands.getstatusoutput('monit summary | grep ^Process')        
                print
                print output
            
        elif is_config == 'T':
            show_timedate()
            is_config = raw_input ('\nWould you like to configure NTP Server(y/n)> ').strip()
            while is_config != 'y' and is_config != 'n':
                is_config = raw_input("Provide the correct option (y/n)> ").strip()
            
            if is_config == 'y':
                config_timedate()
                show_timedate()

        elif is_config == 'E':
            show_mailrelay()
            is_config = raw_input ('\nWould you like to configure mailserver relay(y/n)> ').strip()
            while is_config != 'y' and is_config != 'n':
                is_config = raw_input("Provide the correct option (y/n)> ").strip()
            
            if is_config == 'y':
                config_mailrelay()
                show_mailrelay()

        elif is_config == 'L':
            show_SSL()
            is_config = raw_input ('\nWould you like to configure SSL properties(y/n)> ').strip()
            while is_config != 'y' and is_config != 'n':
                is_config = raw_input("Provide the correct option (y/n)> ").strip()
            
            if is_config == 'y':
                config_SSL()
                show_SSL()

        elif is_config == 'Q':
            sys.exit(0)




